<template>
    <div class="centre font f16">
        <div class="bg-fff bor pl-10 pt-10 pr-10 pb-5">
            <div class="flex jc-sb">
                <div>
                    <el-button plain @click="add">New</el-button>
                    <el-button plain @click="save">Save</el-button>
                    <el-button type="primary" @click="open()" plain>Add to Order</el-button>
                    <el-button type="primary" @click="AddToQuotation" plain class="addQuotation">Add to
                        Quotation</el-button>
                    <el-popconfirm title="Sure to delete?" @confirm="del">
                        <template #reference>
                            <el-button type="primary" plain class="del">Delete</el-button>
                        </template>
                    </el-popconfirm>
                </div>
                <div class="flex jc-e">
                    <el-select v-model="leading" :disabled="store.type != 2" @change="unifiedLeading" class="w60p"
                        placeholder="LEADING">
                        <el-option v-for="item in newLeading" :key="item.label" :label="item.label" :value="item.label" />
                    </el-select>
                </div>
            </div>
            <p class="fwb f70 mt-5">RFQ DETAIL {{ rfqId }} of {{ centerTable.length - 1 }} Quoted</p>
            <!-- 表格 -->
            <el-table :data="centerTable" v-loading="loading" @cell-click="table" @cell-mouse-enter="hover"
                :row-class-name="rfqList" height="53.8vh" @selection-change="row" style="width: 100%;">
                <el-table-column type="selection" width="30" />
                <el-table-column label="MODEL" min-width="170">
                    <template v-slot="model">
                        <el-select v-model="model.row.product.product_id"
                            :disabled="model.row.item.purchase_price != '' || store.type == 3" @change="chModel"
                            :remote-method="getModel" remote filterable placeholder="MODEL">
                            <el-option v-for="item in newModel" :key="item.id" :label="item.label" :value="item.id" />
                        </el-select>
                    </template>
                </el-table-column>
                <el-table-column label="BRAND" min-width="130">
                    <template v-slot="brand">
                        <el-select v-model="brand.row.brand.brand_id"
                            :disabled="brand.row.item.purchase_price != '' || store.type == 3" :remote-method="getBrand"
                            remote filterable placeholder="BRAND">
                            <el-option v-for="item in newBrand" :key="item.id" :label="item.label" :value="item.id" />
                        </el-select>
                    </template>
                </el-table-column>
                <el-table-column label="QTY" min-width="80">
                    <template v-slot="qty">
                        <el-input v-model="qty.row.Qty" :disabled="qty.row.item.purchase_price != '' || store.type == 3"
                            placeholder="QTY" />
                    </template>
                </el-table-column>
                <el-table-column label="BUYER" min-width="185">
                    <template v-slot="buyer">
                        <el-select v-model="buyer.row.purchaser_id_list" @change="changeBrand($event,table)" :disabled="store.type != '1' || store.type == '3'"
                            @remove-tag="delBuyer" @visible-change="getBuyer" collapse-tags collapse-tags-tooltip
                            placeholder="BUYER" multiple>
                            <el-option v-for="item in newBuyer" :key="item.id" :label="item.label" :value="item.id" />
                        </el-select>
                    </template>
                </el-table-column>
                <el-table-column label="PRICE" min-width="80">
                    <template v-slot="price">
                        <el-input v-model="price.row.item.purchase_price" :disabled="store.type == '4' || store.type == '3'"
                            placeholder="PRICE" />
                    </template>
                </el-table-column>
                <el-table-column label="LEADING" min-width="120">
                    <template v-slot="leading">
                        <el-select v-model="leading.row.item.leadingtime" :disabled="store.type != '3' && store.type != '1'"
                            filterable placeholder="LEADING">
                            <el-option v-for="item in newLeading" :key="item.label" :label="item.label"
                                :value="item.case" />
                        </el-select>
                    </template>
                </el-table-column>
                <el-table-column label="CONDITION" min-width="150">
                    <template v-slot="condition">
                        <el-select v-model="condition.row.item.product_condition"
                            :disabled="store.type != '3' && store.type != '1'" filterable placeholder="CONDITION">
                            <el-option v-for="item in newCondition" :key="item.label" :label="item.label"
                                :value="item.case" />
                        </el-select>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <!-- 图表 -->
        <div ref="main" v-loading="loadingFigure" class="w100p mt-10  pt-5 main" style="height: 30vh"></div>

        <!-- 添加订单弹窗 -->
        <AddOrderVue ref="AddOrder" :newLeading="newLeading" :newCondition="newCondition"></AddOrderVue>

        <!-- 添加到报价弹窗 -->
        <AddQuotationVue ref="AddQuotation" @quote="quote" :newLeading="newLeading" :newCondition="newCondition">
        </AddQuotationVue>
    </div>
</template>

<script setup>
import { ref, watch, onMounted } from "vue";
import AddOrderVue from "./components/AddOrder.vue";
import AddQuotationVue from "./components/AddQuotation.vue";
import { ElMessage } from 'element-plus'
import * as $axios from '../../../api/index'
import useBrand from '../../../hooks/useBrand'
import useModel from '../../../hooks/useModel'
//  按需引入 echarts
import * as echarts from "echarts";
import custom from '../../../assets/custom.json'
import { useDemoStore } from '../../../pinia/index'
const store = useDemoStore()
echarts.registerTheme('custom', custom)

const props = defineProps({
    rfqId: Number
})

onMounted(() => {
    getBuyer() //触发getBuyer事件把采购id变成采购名
    getBrand()
    getModel()
})

// 加载
const loading = ref(true)
const loadingFigure = ref(true)

// 表格数据
const centerTable = ref([])
const product = () => {
    loading.value = true
    loadingFigure.value = true
    // console.log(props)
    const data = {
        token: store.token,
        id: props.rfqId
    }
    $axios.$Product(data).then(res => {
        loading.value = false
        console.log(res)
        res.Status != 0 && figure()
        if (res.Status != 0) return
        centerTable.value = res.data.data
        product_id.value = centerTable.value[0] && centerTable.value[0].product_id  //图表id
        model.value = centerTable.value[0] && centerTable.value[0].product.model  //图表标题
        figure() //触发获取图表数据的事件
        leading.value = ''  //清空指标
        if (!props.rfqId) return
        centerTable.value.push(
            {
                "Qty": '',
                "product": {

                },
                "index": Math.round(Math.random() * (9000 - 100) + 100),
                "purchaser_array": {

                },
                "purchaser_id_list": [],
                "brand": {
                    "brand_name": "",
                    "filter": "",
                },
                "item": {
                    "leadingtime": "",
                    "purchase_price": ''
                }
            })
    })
}

// 监听属性
watch(props, () => {
    product()
})

// model选项框，最后一行加一条
const chModel = () => {
    const length = centerTable.value[centerTable.value.length - 1].product.product_id
    // 判断最后一个model框有没有值，有就新增一条空的输入框
    if (length) {
        centerTable.value.push({
            "Qty": '',
            "product": {

            },
            "index": Math.round(Math.random() * (9000 - 100) + 100),
            "purchaser_array": [{

            }],
            "brand": {
                "brand_name": "",
                "filter": "",
            },
            "item": {
                "leadingtime": "",
                "purchase_price": ''
            }
        })
    }
}

// 删除采购
const delBuyer = (p) => {
    const name = array.value.map(item => {
        return item.id
    })
    const index = name.indexOf(p)
    if (array.value[index] != undefined) {
        const data = {
            token: store.token,
            inquiry_item_info_id: array.value[index].inquiry_item_info_id
        }
        $axios.$pollingDel(data).then(res => {
            array.value.splice(index, 1)
        })
    }
}

// 采购多选框，选择触发
// const changeBrand = (val,arr)=>{
//     console.log(val,arr)
// }


// table 鼠标经过时触发的
const array = ref([])
const hover = (data) => {
    array.value = data.purchaser_array
}

// 复选框
const InquiryOfId = ref([])   //询盘id
const random = ref([])
const row = (data) => {
    InquiryOfId.value = []
    random.value = []
    data.forEach((item) => {
        if (item.product.model && Array.isArray(item.purchaser_array) && !item.index) {
            item.purchaser_array.forEach(id => {
                InquiryOfId.value.push(id.inquiry_item_info_id)
                // console.log(id.inquiry_item_info_id)
            })
        } else {
            random.value.push(item.index)
        }
    })
}

// 点击表格
const product_id = ref('') //图表数据
const inquiry_item_info_id = ref('')
const model = ref('') //图表标题
const table = (data) => {
    // console.log(data)
    product_id.value = data.product_id
    inquiry_item_info_id.value = data.inquiry_item_info_id
    model.value = data.product.model
    figure()
    init()
    console.log(data)
}

// 表格高亮
const rfqList = ({
    row,
    rowIndex,
}) => {
    // console.log(inquiry_item_info_id.value)
    if (row.product_id === product_id.value) {
        return 'success-row'
    }
    return ''
}


// model
var newModel = ref([])
const getModel = (text) => {
    newModel.value = { newModel } = useModel(text)
}

// brand
var newBrand = ref([])
const getBrand = (text) => {
    newBrand.value = { newBrand } = useBrand(text)
}

//Buyer(获取销售与采购人员列表)
const newBuyer = ref([])
const getBuyer = () => {
    const data = {
        token: store.token,
        keywords: '采购'
    }
    $axios.$userUser_list(data).then(res => {
        newBuyer.value = res.data.map(item => {
            return {
                'label': item.name,
                'id': item.id
            }
        })
    })
}


// Leading
const newLeading = [
    {
        case: "一周有效",
        label: "+1 week"
    },
    {
        case: "三个月有效",
        label: "+3 mouth"
    },
    {
        case: "今天有效",
        label: "+1 day"
    },
    {
        case: "三天有效",
        label: "+3 day"
    },
    {
        case: "五天有效",
        label: "+5 day"
    },
    {
        case: "一个月有效",
        label: "+1 mouth"
    },
    {
        case: "半年有效",
        label: "+6 mouth"
    },
]

// Condition(状态)
const newCondition = [
    {
        case: "QB全新保内",
        label: "New Sealed Under Guarantee"
    },
    {
        case: "QG全新过保",
        label: "New Sealed Beyond Guarantee"
    },
    {
        case: "QK全新开封保内",
        label: "New Unsealed Under Guarantee"
    },
    {
        case: "QKG全新开封过保",
        label: "New Unsealed Beyond Guarantee"
    },
    {
        case: "F翻新",
        label: "Refurbish"
    },
    {
        case: "E二手",
        label: "Used"
    },
    {
        case: "J兼容",
        label: "Substitute"
    },
    {
        case: "G高仿无牌",
        label: "High Copy Blank Brand"
    },
    {
        case: "GD高仿带牌",
        label: "High Copy With Brand"
    },
    {
        case: "S升级",
        label: "Upgrade"
    },
    {
        case: "W无货",
        label: "Discontinued"
    }
]

// 新增
const addis = ref(true)
const add = () => {
    if (addis.value) {
        addis.value = false
        save()
        centerTable.value = []
        for (let i = 0; i <= 5; i++) {
            centerTable.value.push({
                "Qty": '',
                "inquiry_id": '',
                "msg": 1,
                "product": {
                },
                "purchaser_array": {},
                "purchaser_id_list": [],
                "brand": {
                    "brand_name": "",
                    "filter": "",
                },
                "item": {
                    "leadingtime": "",
                    "purchase_price": ''
                }
            })
        }
    }
    // console.log(centerTable.value)
}

// 需要上传的数据
const dataArr = (arr) => {
    console.log(arr)
    newArr.value = arr.map(item => {
        return {
            "product_id": item.product.product_id,
            "brand_id": item.brand.brand_id,
            "inquiry_id": item.inquiry_id || '',
            "purchaser_id": item.id || '',
            "inquiry_item_info_id": item.inquiry_item_info_id || '',
            'model': item.product.model,
            'brand': item.brand.brand_name,
            'qty': item.Qty || 0,
            'purchase_price': item.item.purchase_price || '',
            'leadingtime': item.item.leadingtime || '',
            'product_condition': item.item.product_condition || '',
            "risk": "稳妥",
            "Effective": "三天有效",
            "Reliability": "牢靠"
        }
    })
}

// save 保存
const newArr = ref([])
const saveState = ref(true)
const save = () => {
    const arr = ref([])
    centerTable.value.forEach((items) => {
        // console.log(items)
        // 判断是否有model有就是要进行提交的
        if (items.product.product_id) {
            if (items.product.product_id && items.brand.brand_id) {
                saveState.value = true
                if (items.purchaser_id_list.length != 0) {
                    items.purchaser_id_list.forEach((name, index) => {
                        arr.value.push({
                            ...items,
                            id: name,
                            inquiry_item_info_id: items.purchaser_array[index] && items.purchaser_array[index].inquiry_item_info_id
                        })
                        // console.log(arr.value)
                        dataArr(arr.value)
                    })
                } else {

                    arr.value.push({
                        ...items,
                    })
                    dataArr(arr.value)
                }
            } else {
                saveState.value = false
            }
        }
    });

    console.log(centerTable.value)
    // console.log(newArr.value[0].inquiry_id)
    if (newArr.value.length != 0 && saveState.value) { //判断数组是否有数据
        leading.value = ''
        const data = {
            "product": newArr.value,
            'token': store.token,
            "customer_id": 5,
            "inquiry_id": centerTable.value[0].msg == 1 ? '' : props.rfqId
        }

        if (centerTable.value[0].msg) { //新建
            $axios.$add(data).then(res => {
                if (res.Status == 0) {
                    emits('save')
                    addis.value = true
                    // product()
                    ElMessage({
                        message: 'Successful preservation',
                        type: 'success',
                    })
                } else {
                    ElMessage({
                        message: 'Save the error',
                        type: 'warning',
                    })
                }
            })
        } else { //更改保存
            // console.log(centerTable.value[0].msg)
            $axios.$add(data).then(res => {
                if (res.Status == 0) {
                    centerTable.value[0].msg == 1 || product()
                    ElMessage({
                        message: 'Successful preservation',
                        type: 'success',
                    })
                } else {
                    ElMessage({
                        message: 'Save the error',
                        type: 'warning',
                    })
                }
            })
        }
    } else if (props.rfqId) {
        // var time2 = new Date()
        // if (time2 - time.value >= 5000) {
        ElMessage({
            message: 'Please choose model brand',
            type: 'warning',
        })
        //     time.value = time2;
        // }
    }
}

// 新增订单转询盘后触发该事件，然后更新页面
const quote = () => {
    emits('save')
}

const emits = defineEmits(['save'])

// 删除
const del = () => {
    if (InquiryOfId.value.length > 0 || random.value.length > 0) {
        if (InquiryOfId.value && InquiryOfId.value.length > 0) {
            const data = {
                token: store.token,
                inquiry_item_info_id: InquiryOfId.value
            }
            // console.log(centerTable.value)
            $axios.$pollingDel(data).then(res => {
                if (res.Status == 0) {
                    InquiryOfId.value.forEach(item => {
                        const index = centerTable.value.findIndex(arr => arr.inquiry_item_info_id == item)
                        index != -1 && centerTable.value.splice(index, 1)
                    })
                    // product()
                    ElMessage({
                        message: 'successfully delete',
                        type: 'success',
                    })
                }
                // console.log(res)
            })
        }
        if (isArray(random.value) && random.value.length > 0) {
            random.value.forEach(item => {
                const index = centerTable.value.findIndex(arr => arr.index == item)
                index != -1 && centerTable.value.splice(index, 1)  //删除数组里面的成员
            })
        }
    } else {
        ElMessage({
            message: 'Please choose',
            type: 'warning',
        })
    }

}

// 批量更改指标
const leading = ref('')
const unifiedLeading = (data) => {
    centerTable.value.forEach(item => {
        if (item.product.model) {
            item.item.leadingtime = data
        }
        // console.log(item)
    })
}

// 图表数据
const figureData = ref([])
const figure = () => {
    loadingFigure.value = true
    const data = {
        token: store.token,
        product_id: product_id.value
    }
    $axios.$offer(data).then(res => {
        loadingFigure.value = false
        // console.log(res.data)
        figureData.value = res.data
        init()
    })
}

// 暴露方法
defineExpose({
    product,
})

// 添加订单弹窗
const AddOrder = ref()
const open = () => {
    AddOrder.value.open()
}

// 添加到报价弹窗
const AddQuotation = ref()
const AddToQuotation = () => {
    AddQuotation.value.poseQuotation()
}


const main = ref() // 使用ref创建虚拟DOM引用，使用时用main.value

// 图表数据
var myChart
const init = () => {
    if (myChart != null && myChart != "" && myChart != undefined) {
        myChart.dispose();//销毁
    }
    myChart = echarts.init(main.value, 'custom');

    var option = {
        title: {
            text: model.value
        },
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'cross',
                label: {
                    backgroundColor: '#fff'
                }
            }
        },
        legend: {
            data: ['Historical inquiry']
        },
        toolbox: {
            feature: {
                saveAsImage: {}
            }
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
        },
        xAxis: [
            {
                type: 'category',
                boundaryGap: false,
                data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
            }
        ],
        yAxis: [
            {
                type: 'value'
            }
        ],
        series: [
            {
                name: 'Historical inquiry',
                type: 'line',
                stack: 'Total',
                areaStyle: {},
                emphasis: {
                    focus: 'series'
                },
                data: figureData.value
            }
        ]
    };
    option && myChart.setOption(option);
    window.addEventListener("resize", myChart.resize) //自动缩放

}


</script>

<style lang="less">
.el-input__inner {
    font-family: 'swis';
}
// .el-table .cell{
//     padding: 0;
// } 
</style>
<style lang="less" scoped>
@import '../rfq.less';
 .boxTable {
        position: relative;
        height: 46.2vh;
        overflow: hidden;

        .table {
            width: 60vw;
        }

        .bbm {
            border-bottom: 1px solid #EBEEF5;
        }

        .operation {
            // border: 1px solid red;
            text-align: center;
            width: 100px;
            right: 17.99%;
            position: fixed;
            background-color: #fff;
        }

        .tabDel {
            // border: 1px solid red;
            width: 100px;
            height: 38px;
            padding-left: 15px;
            padding-right: 15px;
            padding-top: 5px;
            position: fixed;
            display: flex;
            justify-content: center;
            right: 17.99%;
            background-color: #fff;
            z-index: 9;
        }

    }

    .boxTable:hover {
        overflow: auto;
        z-index: 3;
    }

    ::-webkit-scrollbar {
        height: 6px;
        width: 6px;
    }

    ::-webkit-scrollbar-track {
        border-radius: 10px;
    }

    ::-webkit-scrollbar-thumb {
        border-radius: 10px;
        background-color: #C8C9CC;
    }


.w8p {
    width: 8%;
}

.w6p {
    width: 6.7%;
}

.w9p {
    width: 9%;
}

.w12p {
    width: 12.8%;
}

.w16p {
    width: 16.2%;
}
</style>